<?php
if (!class_exists('FileManager'))
{
	require_once 'System/Classes/HTML/Form/Elements/FileManager.php';
}

if (!class_exists('CMSImage'))
{
	require_once 'System/Classes/CMSImage.php';
}

class ImagesManager extends FormElement
{
	static private $bLoadJavaScript = true;

	public function __construct($name, array $value = array(), $selected = null, $properties = array())
	{
		parent::__construct($name, array_merge(array('images' => $value, 'selected' => $selected), $properties));
	}

	public function __toString()
	{
		if (self::$bLoadJavaScript)
		{
			self::$bLoadJavaScript = false;

			HeaderManager::addHeader(HeaderManager::X_JAVASCRIPT, 'Lib/Script/Edit/ImagesManager.js');
			HeaderManager::addHeader(HeaderManager::X_CSS, 'Lib/Style/Edit/ImagesManager.css');
		}

		$name = $this->name;

		$className = 'form imagesmanager';

		if ($this->getProperty('class'))
		{
			$className .= ' ' . $this->getProperty('class');
		}

		$html = '
			<div id="imagesmanager_' . $name . '_container" class="' . $className . '">
				<div class="imagesmanager_container">
					<div class="imagesmanager_container_inner">
						<div class="imagesmanager_storage"></div>
						<input type="hidden" name="imagesmanager_selected" value="' . $this->getProperty('selected') .'" />';

		$hasValue = true;

		$images = $this->getProperty( 'images' );

		if (is_array( $images ) && !empty( $images ))
		{
			$html .= '
				<ul>';

			foreach ($images as $file)
			{
				if( $file instanceof File ) {
					$fullPath = $file->getFullPath();

					if (!file_exists($fullPath))
					{
						continue;
					}

					$newSize = CMSImage::getSize(getImageSize($fullPath), 64);

					$marginTop = 64 - $newSize[1];

					$html .= '
						<li>
							<div>
								<div>
									<img src="' . $file->getImageResized(64, 64) . '" id="imagesmanager_' . $name . '_image_' . $file->id . '" alt="" width="' . $newSize[0] . '" height="' . $newSize[1] . '" style="margin-top: ' . $marginTop . 'px;" class="imagesmanager_image" />
								</div>
							</div>
						</li>';
				}
			}

			$html .= '
				</ul>';
		}
		else
		{
			$hasValue = false;
		}

		$html .= '
			<p class="imagesmanager_no_images"' . ($hasValue ? ' style="display: none;"' : '') . '>##imagesmanager_no_images##</p>';

		$filemanager = new FileManager('imagesmanager_' . $name . '_filemanager', '##imagesmanager_add_image##');

		$html .= '
				<div class="imagesmanager_clear"></div>
			</div>
		</div>';

		$html .= '
			<div class="imagesmanager_actions">
				' . $filemanager . ' <img src="Lib/Images/Icons/add.png" alt="" />
			</div>
			<div class="imagesmanager_clear"></div>
		</div>';

		return $html;
	}
}